package com.ajx.todo.example;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ajx.ablibrary.net.Api;
import com.ajx.todo.R;
import com.ajx.todo.utils.DesTest;
import com.anjuxing.platform.common.util.security.DESCUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;


import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by lai on 2017/9/9.
 */

public class ExampleFragment extends Fragment {
    private static final String TAG = "ExampleFragment";
    private RecyclerView rvExampleList;
    private List<String> examples = new ArrayList<>();
    private ExampleAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.frag_example, container, false);
        rvExampleList = ((RecyclerView) inflate.findViewById(R.id.rv_example_list));
        rvExampleList.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new ExampleAdapter(examples);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                //test1();
                if (position==0){
                    test2(1);
                }
                if (position==1){
                    testJM();
                }

            }
        });
        rvExampleList.setAdapter(adapter);
        return inflate;
    }

    //range
    private void test2(final int limit) {
        Log.e(TAG, "test2当前批次: " + limit);

        Api.downloadWhiteName(limit).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        String string = responseBody.string();
                        WNRES wnres = new Gson().fromJson(string, WNRES.class);
                        int total = wnres.getTotal();
                        int size = wnres.getSize();
                        Log.e(TAG, "本次下载 " + wnres.getDatas().size() + "条");
                        int times = 0;
                        double yu = total * 1.0 / size;
                        if (total % size == 0) {
                            times = (int) yu;
                        } else {
                            times = (int) yu + 1;
                        }
                        Log.e(TAG, "总共 :" + total + ", 一次下载 " + size + "条 ，要下载" + times + "次");
                        if (limit == 1) {
                            //downOther(times);
                            downloadOther(times);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.e(TAG, "accept: " + throwable.getMessage());
                    }
                });
    }

    private void downloadOther(int times) {
        final List<WNRES.CardBean> cardBeans = new ArrayList<>();
        final boolean[] hasError = {false};
        Observable.range(1, times).flatMap(new Function<Integer, ObservableSource<ResponseBody>>() {

            @Override
            public ObservableSource<ResponseBody> apply(Integer integer) throws Exception {
                return Api.downloadWhiteName(integer);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        String string = responseBody.string();
                        Log.e(TAG, "accept: " + string);
                        WNRES wnres = new Gson().fromJson(string, WNRES.class);
                        if ("1".equals(wnres.getResult())) {
                            wnres.getDatas();
                            cardBeans.addAll(wnres.getDatas());
                        } else {
                            hasError[0] = true;
                            Log.e(TAG, "accept: 出错了");
                            cardBeans.clear();
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hasError[0] = true;
                        Log.e(TAG, "accept: 出错了");
                        cardBeans.clear();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        if (hasError[0]) {
                            Log.e(TAG, "下载出错了");
                            cardBeans.clear();
                        } else {
                            Log.e(TAG, "下载成功了: " + cardBeans.size());
                        }
                    }
                });

    }
    public void testJM(){

        String decrypt = DESCUtils.encrypt("123456");
        Log.e(TAG, "testJM: "+decrypt);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        examples.clear();
        examples.add("android component arc");
        examples.add("umeng");
        examples.add("round button");
        examples.add("test");
        adapter.notifyDataSetChanged();
    }

    class ExampleAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public ExampleAdapter(@Nullable List<String> data) {
            super(R.layout.item_example_title, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tv_example_title, item);
        }
    }

    class WNRES {

        private String result;
        private String message;
        private int total;
        private int limit;
        private int size;
        private List<CardBean> datas;

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }

        public int getLimit() {
            return limit;
        }

        public void setLimit(int limit) {
            this.limit = limit;
        }

        public int getSize() {
            return size;
        }

        public void setSize(int size) {
            this.size = size;
        }

        public List<CardBean> getDatas() {
            return datas;
        }

        public void setDatas(List<CardBean> datas) {
            this.datas = datas;
        }

        public class CardBean {
            /**
             * cardNo : ab316ccf5318c4c0
             * type : 2
             * status : 0
             */

            private String cardNo;
            private String type;
            private String status;

            public String getCardNo() {
                return cardNo;
            }

            public void setCardNo(String cardNo) {
                this.cardNo = cardNo;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }

            public String getStatus() {
                return status;
            }

            public void setStatus(String status) {
                this.status = status;
            }
        }
    }
}
